import VueRouter from 'vue-router'
import Vue from 'vue'

import Layout from '@/views/layout'
import Login from '@/views/login'
import Dashboard from '@/views/dashboard'
import Article from '@/views/article'

import store from '@/store'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    {
      path: '/',
      component: Layout,
      redirect: '/dashboard',
      children: [
        { path: 'dashboard', component: Dashboard },
        { path: 'article', component: Article }
      ]
    }
  ]
})

// 这里可以写路由导航拦截的逻辑了
// 全局前置守卫  ==> 进入路由之前，拦截
router.beforeEach((to, from, next) => {
  // 这里取token，直接从vuex中取就好了 ==> 需要导入store
  const token = store.state.user.token
  console.log(token)
  // from 从哪里来
  // to  去哪儿
  // next 放不放你走
  // 没有token，拦截到 登录
  if (to.path !== '/login' && !token) {
    next('/login')
  } else {
    next()
  }
})

export default router
